/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable no-nested-ternary */
import { Flex, Spin, Tabs } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';

import modelService from '@/api/services/modelService';
import workbenchService from '@/api/services/workbenchService';
import {
  GetDefaultListConfig,
  GetDefaultListConfigList,
  GetDefaultListRes,
  GetWorkBenhList,
} from '@/common';
import { SvgIcon } from '@/components/icon';
import NotData from '@/components/NotData';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useTiangongRole } from '@/hooks/useTiangongRole';
import JoyrideGuide from '@/pages/components/joyride-guide';
import { useInitializeData } from '@/store/configStore';
import { useUserInfo, useUserState } from '@/store/userStore';
import { eventBus, EventNameEnum } from '@/utils/eventBus';

import AppSearch from './components/appSearch';
import MobileContent from './components/MobileContent';
import MobileHeader from './components/MobileHeader';
import ModelFailure from './components/ModelFailure';
import RightDown from './components/rightDown';
import WorkbenchAll from './components/workbenchAll';
import './style/index.css';

import type { TabsProps } from 'antd';

type PositionType = 'left' | 'right';
interface pageType {
  page: number;
  page_size: number;
  searchText: string;
  app_type: string | null;
  app_workbench_type: string;
  app_status: string | null;
  tags: string;
  templateSourceType: string | null;
}

export default function WordBoard() {
  const { windowWidth, isPc } = useWindowWidth();
  const [position, setPosition] = useState<PositionType[]>(['left', 'right']);
  const { role } = useUserInfo();

  const [activeFilter, setActiveFilter] = useState<string>('all');
  const [activeTag, setActiveTag] = useState<string>('');
  const [activePublicTag, setActivePublicTag] = useState<string>('全部');

  const [appList, setAppList] = useState<GetWorkBenhList[]>([]);

  const [isNoData, setIsNoData] = useState<boolean>(false); // 是否有数据
  const [flag, setflag] = useState<boolean>(false); // 用于防止多次触发
  const [total, setTotal] = useState<number>(0);

  const [isLoading, setIsLoading] = useState<boolean>(false);

  const [value, setValue] = useState('');

  const abortControllerRef = useRef<AbortController | null>(null);

  const [defaultModelData, setDefaultModelData] = useState<GetDefaultListRes>();

  const [defaultModelShow, setDefaultModelShow] = useState<number>(-20);

  const [modelTips, setModelTips] = useState({
    defaultModel: false,
    defaultModelFailure: false,
    modelFailure: false,
  });

  const [modelDefaultFailure, setModelDefaultFailure] = useState<GetDefaultListConfigList[]>([]);

  const [modelFailure, setModelFailure] = useState<GetDefaultListConfig[]>([]);

  const [providerFailure, setProviderFailure] = useState<any[]>([]);

  const [providerInfo, setProviderInfo] = useState<GetDefaultListConfig[]>([]); // 使用 useState 管理 modelInfo 集合

  // 根据License Edition标识位显示/隐藏模块
  const initializeData = useInitializeData();
  const { use_legacy_version, license_edition, is_knowledge_manager, is_knowledge_reviewer } =
    initializeData;

  const isLegacyVersion = useMemo(() => {
    if (!license_edition) {
      return false;
    }
    return !!use_legacy_version;
  }, [use_legacy_version, license_edition]);

  useEffect(() => {
    getModelInfo();
  }, []);

  const { userInfo } = useUserState();

  const adminUser = useMemo(() => userInfo.role?.code === 'super_admin', [userInfo]);
  const normalUser = useMemo(() => userInfo.role?.code === 'normal_user', [userInfo]);

  // 新增逻辑：从本地缓存读取天工角色状态
  const { isTiangongManager, isTiangongAdmin } = useTiangongRole();

  const isMyAgnge = useMemo(() => {
    // 更新逻辑：合并天工角色状态和原有的知识库管理员/审核员状态
    return Boolean(isPc && (isTiangongManager || is_knowledge_manager || is_knowledge_reviewer));
  }, [isPc, is_knowledge_manager, is_knowledge_reviewer, isTiangongManager]);
  const [defaultPage, setDefaultPage] = useState<pageType>({
    page: 1,
    page_size: 29,
    searchText: '',
    app_type: null, // 应用类型
    app_workbench_type: isTiangongAdmin
      ? 'public'
      : isTiangongManager
      ? 'manager'
      : isMyAgnge
      ? 'manager'
      : 'public', // 应用模板类型
    app_status: null, // 审核状态
    tags: '',
    templateSourceType: null,
  });
  const [keys, setKeys] = useState(
    isTiangongAdmin ? '3' : isTiangongManager ? '1' : isMyAgnge ? '1' : '3',
  );

  // 监听 isMyAgnge 变化，修正初始页签与查询类型，避免"权限就绪后仍沿用旧类型"的问题
  useEffect(() => {
    const targetKey = isTiangongAdmin ? '3' : isTiangongManager ? '1' : isMyAgnge ? '1' : '3';
    const targetType = isTiangongAdmin
      ? 'public'
      : isTiangongManager
      ? 'manager'
      : isMyAgnge
      ? 'manager'
      : 'public';
    if (keys !== targetKey || defaultPage.app_workbench_type !== targetType) {
      setKeys(targetKey);
      setAppList([]);
      setDefaultPage((prev) => ({
        ...prev,
        page: 1,
        app_workbench_type: targetType,
      }));
    }
  }, [isMyAgnge, isTiangongManager, isTiangongAdmin]);
  const getModelInfo = async () => {
    const res = await modelService.getConnection();
    // const res = await Promise.all([modelService.getDefaultList(), modelService.getConnection()]);
    // const defaultModel = res[0];
    const modelConnection = res;
    let height = -20;
    const modelStatus = {
      defaultModel: false,
      defaultModelFailure: false,
      modelFailure: false,
    };

    // const defaultModelFillter = Object.values(defaultModel).some((item) => item === null);

    // setDefaultModelData(defaultModel);

    // if (defaultModelFillter) {
    //   height += 174;
    //   modelStatus.defaultModel = true;
    // }

    // if (modelConnection.default.length > 0) {
    //   height += 94;
    //   modelStatus.defaultModelFailure = true;

    //   // 生成 defaultModelList
    //   const defaultModelList = modelConnection.default.reduce(
    //     (acc: GetDefaultListConfigList[], modelDefault) => {
    //       const matchedConfig = modelConnection.config.find(
    //         (modelConfig) => modelConfig.model === modelDefault,
    //       );
    //       return matchedConfig ? [...acc, ...matchedConfig.list] : acc;
    //     },
    //     [],
    //   );
    //   setModelDefaultFailure(defaultModelList);
    // }

    if (modelConnection.config.length > 0) {
      // 获取模型列表和创建的列表
      const [modelList, modelCreateList] = await Promise.all([
        modelService.getModelList({
          offset: -1,
          page: 1,
          pageSize: 999999,
          searchText: '',
        }),
        modelService.getCreatedList({
          offset: -1,
          page: 1,
          pageSize: 999999,
          searchText: '',
        }),
      ]);

      // 构建一个快速查找的 Map，以模型名称为 key
      const modelMap = new Map(
        modelList.list.map((modelInfo: any) => [modelInfo.metadata.name, modelInfo.metadata]),
      );

      const list: any[] = [];
      const modelInfoSet = new Set<any>(); // 使用 Set 代替数组去重

      for (const config of modelConnection.config) {
        const modelInfo = modelMap.get(config.model);
        if (modelInfo) {
          // 查找 `list` 中是否已经存在当前 `model`
          const existingItem = list.find((item) => item.model === modelInfo.model);

          if (existingItem) {
            // 如果存在，向 `configs` 中添加 `config`
            existingItem.modelList = [...config.list, ...existingItem.modelList];
          } else {
            // 如果不存在，添加新的项
            list.push({
              provider: modelInfo.provider,
              model: modelInfo.model,
              modelList: [...config.list], // 初始化 configs 数组
            });
          }
          modelInfoSet.add(modelInfo); // Set 会自动去重
        }
      }

      const validProvidersList = modelCreateList.list.filter(
        (item: any) =>
          [...modelInfoSet].some((info) => info.provider === item.name) && item.status === '1',
      );

      // 筛选出符合条件的 modelInfo 对象
      const validProviders = validProvidersList.map((item: any) => item.name); // 获取符合条件的 name 列表

      // 如果找到了符合条件的 providers，则返回这些 providers
      if (validProviders.length > 0) {
        // const filteredList = list.filter((item) => validProviders.includes(item.model));
        const filteredList = list;
        const result = modelCreateList.list.filter(
          (item: any) =>
            [...modelInfoSet].some((info) => info.provider === item.name) && item.status === '1',
        );

        setProviderFailure(filteredList);
        // setModelInfoSet(modelInfoSet);
        setProviderInfo(result as unknown as GetDefaultListConfig[]);

        // height += 134;
        height += 72;
        modelStatus.modelFailure = true;
        setModelFailure(modelConnection.config);
      }
    }

    setModelTips(modelStatus);
    setDefaultModelShow(height);
    // setDefaultModelData(defaultModel);
  };

  // 获取应用市场列表
  const getPublic = async () => {
    try {
      const abortController = new AbortController();
      const { signal } = abortController;
      // 如果之前有未完成的请求，取消
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
      abortControllerRef.current = abortController;
      const effectiveType = keys === '1' ? 'manager' : keys === '2' ? 'market' : 'public';
      const params = { ...defaultPage, app_workbench_type: effectiveType };
      const res = await workbenchService.workListApi(params, signal);
      setIsNoData(true);
      setIsLoading(true); // 判断请求是否加载完成
      const isFirstPage = params.page === 1;
      setAppList((prev) => (isFirstPage ? res.app_list : [...prev, ...res.app_list]));
      setflag(false);
      setTotal(res.total);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getPublic();
  }, [defaultPage]);

  // 页面加载完成后添加loaded类名，避免初始动画
  useEffect(() => {
    const timer = setTimeout(() => {
      const tabsElement = document.querySelector('.work-tabs');
      if (tabsElement) {
        tabsElement.classList.add('loaded');
      }
    }, 500); // 增加延迟时间确保页面完全加载
    return () => clearTimeout(timer);
  }, []);

  // 搜索框
  const changeSearchValue = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 拿到搜索的数据
    setDefaultPage((prev) => ({
      ...prev,
      searchText: e.target.value,
      page: 1,
    }));
    setAppList([]);
    setValue(e.target.value);
  };

  const publicTagChange = (data: string) => {
    console.log('data', data);
    setActivePublicTag(data);
    setAppList([]);
    setflag(true);
    setIsLoading(false);
    const baseReset = {
      page: 1,
      page_size: 29,
      searchText: value,
      app_type: null,
      app_workbench_type: 'public',
    };
    let newPageState = {};
    newPageState = {
      ...baseReset,
      tags: data === '全部' ? null : data,
    };
    setDefaultPage((prev) => ({ ...prev, ...newPageState }));
  };
  const tagChange = (data: string) => {
    setActiveTag(data);
    setValue('');
    setAppList([]);
    setflag(true);
    setIsLoading(false);
    const baseReset = {
      page: 1,
      page_size: 29,
      searchText: '',
      app_type: null,
      templateSourceType: null,
      app_workbench_type: keys === '1' ? 'manager' : 'market',
    };
    let newPageState = {};
    if (keys === '1') {
      newPageState = {
        ...baseReset,
        app_status: activeFilter === 'all' ? null : activeFilter,
        tags: data === '全部标签' ? null : data,
      };
    } else {
      newPageState = {
        ...baseReset,
        templateSourceType: activeFilter === 'all' ? null : activeFilter,
      };
    }
    setDefaultPage((prev) => ({ ...prev, ...newPageState }));
  };
  const changeActiveFilter = (data: string) => {
    setActiveFilter(data);
    setValue('');
    setAppList([]);
    setflag(true);
    setIsLoading(false);
    const baseReset = {
      page: 1,
      page_size: 29,
      searchText: '',
      app_type: null,
      templateSourceType: null,
      app_workbench_type: keys === '1' ? 'manager' : 'market',
    };
    let newPageState = {};
    if (keys === '1') {
      newPageState = {
        ...baseReset,
        app_status: data === 'all' ? null : data,
        tags: activeTag === '全部标签' ? null : activeTag,
      };
    } else {
      newPageState = {
        ...baseReset,
        templateSourceType: data === 'all' ? null : data,
      };
    }
    setDefaultPage((prev) => ({ ...prev, ...newPageState }));
  };

  // 这个是复制或删除应用
  eventBus.on(EventNameEnum.addFlagText, (e: any) => {
    const baseReset = {
      page: 1,
      page_size: 29,
      searchText: '',
      app_type: null,
      // app_status: null,
      TemplateSourceType: null,
    };
    const newPageState = {
      ...baseReset,
      app_workbench_type: keys === '1' ? 'manager' : keys === '2' ? 'market' : 'public',
    };
    setAppList([]);
    setDefaultPage((prev) => ({ ...prev, ...newPageState }));
    // 通知去把搜索数据改掉
    setValue('');
  });

  const onscroll = () => {
    if (appList.length >= total) {
      return;
    }
    setDefaultPage((prev) => ({ ...prev, page: defaultPage.page + 1 }));
  };

  const items: TabsProps['items'] = [
    {
      key: '1',
      label: (
        <div className="flex items-center gap-2 ">
          <SvgIcon icon={keys === '1' ? 'myApplicationActive' : 'myApplication'} size={20} />
          我的应用
        </div>
      ),
      children:
        appList.length === 0 && role?.code !== 'super_admin' && role?.code !== 'admin' ? (
          <div className="flex h-[570px] items-center">
            <NotData iconSize={80} textClassName="text-sm" />
          </div>
        ) : (
          <WorkbenchAll
            onScroll={onscroll}
            activeFilter={activeFilter}
            tagChange={tagChange}
            setActiveFilter={changeActiveFilter}
            name={keys}
            isNoData={isNoData}
            appList={appList}
            flag={flag}
            setflag={(value) => setflag(value)}
            height={isPc ? defaultModelShow : 0}
          />
        ),
    },
    ...(isLegacyVersion
      ? []
      : [
          {
            key: '2',
            label: (
              <div className="flex items-center gap-2">
                <SvgIcon
                  icon={keys === '2' ? 'applicationTemplateActive' : 'applicationTemplate'}
                  size={20}
                />
                应用模板
              </div>
            ),
            children: (
              <WorkbenchAll
                onScroll={onscroll}
                activeFilter={activeFilter}
                setActiveFilter={changeActiveFilter}
                name={keys}
                isNoData={isNoData}
                appList={appList}
                flag={flag}
                setflag={(value) => setflag(value)}
                isLoading={isLoading}
                height={isPc ? defaultModelShow : 0}
              />
            ),
          },
        ]),
    {
      key: '3',
      label: (
        <div className="flex items-center gap-2">
          <SvgIcon
            icon={keys === '3' ? 'applicationPlaygroundActive' : 'applicationPlayground'}
            size={20}
          />
          应用广场
        </div>
      ),
      children: (
        <WorkbenchAll
          onScroll={onscroll}
          activeFilter={activeFilter}
          activePublicTag={activePublicTag}
          publicTagChange={publicTagChange}
          name={keys}
          isNoData={isNoData}
          appList={appList}
          flag={flag}
          isLoading={isLoading}
          setflag={(value) => setflag(value)}
          height={isPc ? defaultModelShow : 0}
        />
      ),
    },
  ];
  // 取消
  const cancel = () => {
    // 拿到搜索的数据
    setDefaultPage((prev) => ({
      ...prev,
      searchText: '',
      page: 1,
    }));
    setAppList([]);
  };

  const operations = <AppSearch value={value} changeSearchValue={changeSearchValue} />;

  const OperationsSlot: Record<PositionType, React.ReactNode> = {
    left: (
      <div className="pl-4 pt-2">
        <SvgIcon icon="ic-logo" style={{ width: 36, height: 36 }} />
      </div>
    ),
    right: <RightDown value={value} changeSearchValue={changeSearchValue} cancel={cancel} />,
  };

  const slot = useMemo(() => {
    if (position.length === 0) {
      return null;
    }
    return position.reduce(
      (acc, direction) => ({ ...acc, [direction]: OperationsSlot[direction] }),
      {},
    );
  }, [position]);

  const onChange = (key: string) => {
    setKeys(key);
    // 定义基础重置状态
    const baseReset = {
      page: 1,
      page_size: 29,
      searchText: '',
      app_type: null,
      app_status: null,
      tags: '',
      templateSourceType: null,
    };
    const newPageState = {
      ...baseReset,
      app_workbench_type: key === '1' ? 'manager' : key === '2' ? 'market' : 'public',
    };
    setAppList([]);
    setDefaultPage((prev) => ({ ...prev, ...newPageState }));
    setValue(''); // 通知去把搜索数据改掉
    setActiveFilter('all');
    setActiveTag('全部标签');
    setActivePublicTag('全部');
    setIsLoading(false);
  };

  const changeItem = isTiangongAdmin
    ? items.filter((item) => item.key === '3')
    : isTiangongManager
    ? items.filter((item) => item.key === '1' || item.key === '3')
    : isMyAgnge
    ? items
    : items.slice(-1);

  return (
    <>
      {/* {modelTips.defaultModel && adminUser && (
        <CloudModelConfig defaultModelData={defaultModelData} getDeaultList={getModelInfo} />
      )}
      {modelTips.defaultModelFailure && !normalUser && (
        <ModelDefaultFailure list={modelDefaultFailure} adminUser={adminUser} />
      )} */}

      {!isNoData ? (
        <Flex align="center" gap="middle" className="flex h-full items-center justify-center">
          <Spin size="large" />
        </Flex>
      ) : (
        <>
          {modelTips.modelFailure && !normalUser && isPc && (
            <ModelFailure
              list={providerFailure}
              providerInfo={providerInfo}
              getModelInfo={getModelInfo}
              adminUser={adminUser}
            />
          )}
          <JoyrideGuide />
          <div className="m-auto flex-grow  flex-row">
            {isNoData ? (
              isPc ? (
                <Tabs
                  centered={!isPc}
                  // 如果是天工角色，则不显示右上角的搜索框等操作区域
                  tabBarExtraContent={isTiangongManager ? null : isPc ? operations : slot}
                  // defaultActiveKey="1"
                  items={changeItem}
                  className="work-tabs text-text-4"
                  onChange={onChange}
                  tabBarStyle={{
                    borderBottom: '1px solid #E5E6EB',
                    fontWeight: '400',
                  }}
                />
              ) : (
                <div>
                  <MobileHeader changeSearchValue={changeSearchValue} />

                  <MobileContent
                    onScroll={onscroll}
                    name={keys}
                    appList={appList}
                    flag={flag}
                    isLoading={isLoading}
                    setflag={(value) => setflag(value)}
                    height={isPc ? defaultModelShow : 0}
                  />
                </div>
              )
            ) : (
              <Flex align="center" gap="middle" className="flex h-full items-center justify-center">
                <Spin size="large" />
              </Flex>
            )}
          </div>
        </>
      )}
    </>
  );
}
